<!--
 * @Author: Binggan
 * @Date: 2020-03-01 14:15:47
 * @LastEditors: Binggan
 * @LastEditTime: 2020-03-03 18:54:13
 * @Description: vue-quill-editor富文本编辑器
 -->
<template>
  <quill-editor v-model="content" ref="myQuillEditor" :options="editorOption" @focus="onEditorFocus($event)" @blur="onEditorBlur($event)" @change="onEditorChange($event)">
  </quill-editor>
</template>

<script>
import { addQuillTitle } from "@/assets/js/editor.option.js";
import axios from '@/assets/axios/interceptors'
import { quillEditor } from "vue-quill-editor"; // 调用富文本编辑器
import "quill/dist/quill.snow.css"; // 富文本编辑器外部引用样式  三种样式三选一引入即可
//import 'quill/dist/quill.core.css'
//import 'quill/dist/quill.bubble.css'
import * as Quill from "quill"; // 富文本基于quill

const uploadConfig = {
  action: "/pic/upload", // 必填参数 图片上传地址
  methods: "POST", // 必填参数 图片上传方式
  name: "file", // 必填参数 文件的参数名
  accept: "image/png, image/gif, image/jpeg, image/bmp, image/x-icon" // 可选 可上传的图片格式
};
const handlers = {
  image(val) {
    let self = this;
    let fileInput = this.container.querySelector("input.ql-image[type=file]");
    if (fileInput === null) {
      fileInput = document.createElement("input");
      fileInput.setAttribute("type", "file");
      // 设置图片参数名
      if (uploadConfig.name) {
        fileInput.setAttribute("name", uploadConfig.name);
      }
      // 可设置上传图片的格式
      fileInput.setAttribute("accept", uploadConfig.accept);
      fileInput.classList.add("ql-image");
      // 监听选择文件
      fileInput.addEventListener("change",()=>{
        // 创建formData
        var formData = new FormData();
        formData.append(uploadConfig.name, fileInput.files[0]);
        // 图片上传
        console.log(uploadConfig,fileInput.files[0]);
        console.log(this.quill.getSelection(true).index);
        axios({
            url:uploadConfig.action,
            type:uploadConfig.methods,
            data:formData
        }).then(res=>{
            console.log(res.data);
            if(res.data.errorCode=="0"){
              // 获取光标所在位置
              let length = self.quill.getSelection(true).index;
              //图片上传成功后，img的src需要在这里添加，res.path就是你服务器返回的图片链接。
              self.quill.insertEmbed(length, "image", res.data.data);
              self.quill.setSelection(length + 1);
              fileInput.value = "";
            }
        }).catch(()=>{

        })
        // var xhr = new XMLHttpRequest();
        // xhr.open(uploadConfig.methods, uploadConfig.action, true);
        // // 上传数据成功，会触发
        // xhr.onload = function(e) {
        //   if (xhr.status === 200) {
        //     var res = JSON.parse(xhr.responseText);
        //     let length = self.quill.getSelection(true).index;
        //     //这里很重要，你图片上传成功后，img的src需要在这里添加，res.path就是你服务器返回的图片链接。
        //     self.quill.insertEmbed(length, "image", res.path);
        //     self.quill.setSelection(length + 1);
        //   }
        //   fileInput.value = "";
        // };
        // // 开始上传数据
        // xhr.upload.onloadstart = function(e) {
        //   fileInput.value = "";
        // };
        // // 当发生网络异常的时候会触发，如果上传数据的过程还未结束
        // xhr.upload.onerror = function(e) {};
        // // 上传数据完成（成功或者失败）时会触发
        // xhr.upload.onloadend = function(e) {
        //   // console.log('上传结束')
        // };
        // xhr.send(formData);
      });
      this.container.appendChild(fileInput);
    }
    fileInput.click();
  }
};
export default {
  data() {
    return {
      editor: null, // 富文本编辑器对象
      content: `<p>请输入正文</p>`, // 富文本编辑器默认内容
      reg: /<[^>]+>/g, //用来获取纯文本replace(/<[^>]+>/g, "")
      editorOption: {
        //  富文本编辑器配置
        theme: "snow",
        placeholder: "请输入正文",
        modules: {
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"],
              ["blockquote", "code-block"],
              [{ header: 1 }, { header: 2 }],
              [{ list: "ordered" }, { list: "bullet" }],
              [{ script: "sub" }, { script: "super" }],
              [{ indent: "-1" }, { indent: "+1" }],
              [{ direction: "rtl" }],
              [{ size: ["small", false, "large", "huge"] }],
              [{ header: [1, 2, 3, 4, 5, 6, false] }],
              [{ color: [] }, { background: [] }],
              [{ font: [] }],
              [{ align: [] }],
              ["clean"],
              ["link", "image", "video"]
            ],// 工具栏选项
            handlers: handlers // 事件重写
          }
        }
      }
    };
  },
  props: ["htmlContent"],
  components: {
    quillEditor
  },
  methods: {
    // 准备富文本编辑器
    onEditorReady(editor) {},
    // 富文本编辑器 失去焦点事件
    onEditorBlur(editor) {},
    // 富文本编辑器 获得焦点事件
    onEditorFocus(editor) {},
    // 富文本编辑器 内容改变事件
    onEditorChange(editor) {
      this.$emit("blurHandle", this.content);
    }
  },
  created() {
    this.content = this.htmlContent;
  },
  mounted() {
    addQuillTitle();
    this.editor = this.$refs.myQuillEditor.quill;
  },
  beforeDestroy() {
    this.editor = null;
    delete this.editor;
  }
};
</script>
<style>
.editor {
  line-height: normal !important;
  height: 800px;
}
.ql-snow .ql-tooltip[data-mode="link"]::before {
  content: "请输入链接地址:";
}
.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
  border-right: 0px;
  content: "保存";
  padding-right: 0px;
}

.ql-snow .ql-tooltip[data-mode="video"]::before {
  content: "请输入视频地址:";
}

.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: "14px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
  content: "10px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
  content: "18px";
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
  content: "32px";
}

.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: "文本";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
  content: "标题1";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
  content: "标题2";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
  content: "标题3";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
  content: "标题4";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
  content: "标题5";
}
.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
  content: "标题6";
}

.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
  content: "标准字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
  content: "衬线字体";
}
.ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
  content: "等宽字体";
}
</style>
<style lang="scss" scoped>
</style>